import { setToken, removeToken, getToken } from '@/utils/auth'
import { login, getUserProfile, getUserDetailById } from '@/api/user'
import { resetRouter } from '@/router/index'

const state = {
  // 定义token
  token: getToken() || '', // 共享的token
  userInfo: {} // 用户信息
}

const mutations = {
  setToken(state, token) {
    state.token = token
    // 将token 持久化存储到本地
    setToken(token)
  },

  // 设置用户信息
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },

  // 移除token
  removeToken(state) {
    state.token = ''
    removeToken()
  },

  // 删除用户信息
  reomveUserInfo(state) {
    state.userInfo = {}
  }
}

const actions = {
  async userlogin(store, data) {
    const res = await login(data)
    store.commit('setToken', res.data)
  },

  // 获取用户信息
  async getUserInfo(store, userInfo) {
    // 用户信息
    const res = await getUserProfile(userInfo)
    // console.log(res)
    // 用户个人信息
    const getUserInfo = await getUserDetailById(res.data.userId)
    // console.log(getUserInfo)
    store.commit('setUserInfo', { ...res.data, ...getUserInfo.data })
    // 后端返回的权限信息
    return res.data.roles.menus
  },

  // 退出登录清空token和userInfo
  logout(store) {
    store.commit('removeToken')
    store.commit('reomveUserInfo')
    // 将路由进行重置
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

